package EGS.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;

import javax.swing.JTable;

import org.dom4j.Document;
import org.dom4j.Element;
import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import WORKPLACE.m_panelSonResultState;
import WORKPLACE.stationClient;

public class EGS_execute_service550Impl240924{
	public boolean isUnknowCase = false;
	ExecutorService iExecutorService;
	Document MSG;
	boolean isPanel = false;
	stationClient iClient=null;
	SQLtool sql = null;
	/**
	 * 550 过站履历登记
	 */
	public EGS_execute_service550Impl240924(stationClient nClient, Document MSG_in, ExecutorService executorService, 
			SQLtool goldenSql) throws Exception {
		super();
		sql=goldenSql;
		if(nClient!=null) {
			iClient=nClient;
		}else {
			iClient=null;
		}
		MSG = MSG_in;
		iExecutorService = executorService;
	}

	public Document runCal() {
		String msgClass = "";
		try {
			if (MSG == null) {
				return null;
			}
			Element Mroot = MSG.getRootElement();
			msgClass = Mroot.element("header").attribute("messageClass").getValue();
			String transactionID = Mroot.element("header").attribute("transactionID").getValue();
			String iStation, iSN, iLayer,iState;
			int iiLayer,iiState = 0;

			iStation = Mroot.element("header").element("location").attribute("equipmentName").getValue();

			if (msgClass.equals("550")) {
				iSN = Mroot.element("body").element("panel").attribute("pcbID").getValue();
				iLayer = Mroot.element("body").element("panel").attribute("productSide").getValue();
				iState = Mroot.element("body").element("panel").attribute("state").getValue();
				String iRepair = "0";
				try {
					iRepair = Mroot.element("body").element("panel").attribute("repairType").getValue();
				} catch (Exception e) {
					iRepair = "0";
				}
				String procedure="-1";
				try {
					procedure = Mroot.element("body").element("panel").attribute("procedureNumber").getValue();
					if(procedure.length()<1) {
						procedure="-1";
					}
				}catch(Exception ee) {
					procedure="-1";
				}
				if(procedure.equals("-1")) {
					procedure=iClient.myProcedureNumber;
				}
				Element elePanel = Mroot.element("body").element("panel");
				List<?> sons = elePanel.elements();
				iiLayer = Integer.parseInt(iLayer);
				Mroot.element("body").remove(Mroot.element("body").element("panel"));
				Element eleR = Mroot.element("body").addElement("result");
				boolean isget = false;
				try {
					iiState = Integer.parseInt(iState);
					isget = true;
				}catch(Exception e) {
					String str = errCodeManagement.getErrText("过站电文异常body->panel->state_"+e.getMessage());
					eleR.addAttribute("errorCode", "1");
					eleR.addAttribute("errorText", str);
					eleR.addAttribute("actionCode", transactionID);
					AKSLogs(5500, "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
				}
//				endT = GetTimestamp();
//				diffMS = getDiffMS(startT1, endT);
				if(isget && (iiLayer==-1)) {
					iiLayer=iClient.myLayer;
				}
				if (!isget) {
					;
				} else if (iiLayer != iClient.myLayer) {
					String str = "工单激活面别(" + iClient.myLayer + ")与产品上传面别不一致！";
					eleR.addAttribute("errorCode", "1");
					eleR.addAttribute("errorText", str);
					eleR.addAttribute("actionCode", "0");
					AKSLogs(5500, "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
				} else {
					boolean bState = false;
					if (iiState == 0) {
						bState = true;
					}
					boolean bRepair = false;
					if (iRepair.equals("1")) {
						bRepair = true;
					}
					try {
						boolean icallXRay = false;
						if (
//								(sons.size() <= 1) && 
								(!iClient.isPanel)) {//如果是拼板，即便只有一个子板也按拼板模式分析
							if (sons.size() >0) {
								List<?> errComps = sons;
								Vector<String> iRpComps = new Vector<String>();
								for (int n = 0; n < errComps.size(); n++) {
									String isRpass = "0";
									try {
										isRpass = ((Element) errComps.get(n)).attribute("bRpass").getValue();
									}catch(Exception e) {
										isRpass = ((Element) errComps.get(n)).attribute("Rpass").getValue();
									}
									if (isRpass.equals("1")) {
										String[] strComps = ((Element) errComps.get(n)).attribute("comps").getValue()
												.split(",");
										iRpComps.addAll(Arrays.asList(strComps));
									}
								}
								if (iRpComps.size() > 0) {
									String iMasterNumber=null;//  
									String isqlstr="select masterNumber from vOrderListPanel where "
											+ "panelOrderNumber='" + iClient.activeOrderNumber + "'";
									JTable t1=sql.select(isqlstr);
									if(t1!=null && t1.getRowCount()>0) {
										iMasterNumber = ""+t1.getValueAt(0, 0);
									}
									
									if (iMasterNumber != null && iMasterNumber.length() > 0) {// 查询总成号
										JTable t = sql.select(
												"select partNumber,comps,materialNumber from SPIxRayList where partNumber='"
														+ iMasterNumber + "'");
										if (t != null && t.getRowCount() > 0) {// 下载加严清单中该总成的所有位号
											Vector<String> iXRComps = new Vector<String>();
											for (int m = 0; m < t.getRowCount(); m++) {
												String strXR = "" + t.getValueAt(m, 1);
												if (strXR != null && strXR.length() > 0 && (!strXR.equals("null"))) {
													iXRComps.addAll(Arrays.asList(strXR.split(",")));
												}
											}
											if (iXRComps.size() > 0) {
												for (int m = 0; m < iRpComps.size(); m++) {// 验证是否在加严清单中
													String strr = iRpComps.get(m);
													if (strr != null && strr.length() > 0) {
														if (iXRComps.indexOf(iRpComps.get(m)) >= 0) {
															icallXRay = true;
															m = iRpComps.size() + 1;
														}
													}
												}
											}
										}
									}
								}
							}
							try {
								iClient.uploadState(iSN, bState, bRepair, icallXRay,procedure);// 如果工序是A0200强制重回FCT，除非没有FCT工序
							} catch (Exception ex) {
								if (ex.getMessage().equals("-152")) {
									String realSN = iClient.getSN4Label(iSN);// 如果条码未识别，先查询看看是否为标签
									if (realSN != null) {
										iSN = realSN;
										iClient.uploadState(iSN, bState, bRepair, icallXRay,procedure);
									} else {
										throw ex;
									}
								} else {
									throw ex;
								}
							}
						} else {// 判断是否加严清单中的案例
							m_panelSonResultState[] sonsState = new m_panelSonResultState[sons.size()];
							boolean gResult = true;

							for (int jj = 0; jj < sonsState.length; jj++) {
								if (((Element) (sons.get(jj))).getName().equals("subPanel")) {
									String iPos = ((Element) (sons.get(jj))).attribute("pos").getValue();
									String iResult = ((Element) (sons.get(jj))).attribute("state").getValue();// 0=无异常
									List<?> errComps = ((Element) sons.get(jj)).elements();
									
									sonsState[jj] = new m_panelSonResultState();//
									/**
									 * 	有复判的位号
									 */
									Vector<String> iRpComps =getRepairComps(errComps);//ss
									if (iRpComps.size() > 0) {// 判断是否加严清单中的案例
										Vector<String> iXRComps=getSPIxRayListComps(iPos);
										if (iXRComps.size() > 0) {
											for (int m = 0; m < iRpComps.size(); m++) {// 验证是否在加严清单中
												String strr = iRpComps.get(m);
												if (strr != null && strr.length() > 0) {
													if (iXRComps.indexOf(iRpComps.get(m)) >= 0) {
														icallXRay = true;
														sonsState[jj].callXRay = true;
														if(sonsState[jj].xRayComps.length()>0) {
															sonsState[jj].xRayComps=sonsState[jj].xRayComps+",";
														}
														sonsState[jj].xRayComps=sonsState[jj].xRayComps+iRpComps.get(m);
//														m = iRpComps.size() + 1;// 改成每一个加严清单中的位号都要可查询
													}
												}
											}
										}
									}
									sonsState[jj].pos = Integer.parseInt(iPos);
									sonsState[jj].isPass = false;
									if (iResult != null && iResult.equals("0")) {
										sonsState[jj].isPass = true;
										try {
											String iiRepair = ((Element) (sons.get(jj))).element("errComps")
													.attribute("comps").getValue();
											if (iiRepair != null && iiRepair.length() > 0) {
												sonsState[jj].isRepair = true;
											}
										} catch (Exception a) {
											;
										}
									} else {
										gResult = false;
										sonsState[jj]=getErrCompsInfo(sonsState[jj],errComps);
									}
									if(errComps!=null && errComps.size()>0) {
										iClient.uploadSubPanelResultData(iSN,iPos,errComps);
									}// 自动填充555
								} else {
									sonsState[jj] = new m_panelSonResultState();
								}
								
							}
							if(sons.size()==0) {
								iClient.uploadPanelState(iSN, gResult, bRepair, icallXRay,procedure);
							}else {
								
								if (procedure.equals("A0020") 
//										|| sCl.myProcedureNumber.equals("A0030")
										|| procedure.equals("A0040")) {
									iClient.uploadPanelState(iSN, gResult, bRepair, icallXRay,procedure);
								} else {
//									if(!gResult) {
//										AKSLogs(230810, "" +gXML);
//									}
									iClient.uploadPanelState(iSN, sonsState,procedure);
								}
							}
							
						}
						eleR.addAttribute("errorCode", "0");
						eleR.addAttribute("errorText", "Valid");
						eleR.addAttribute("actionCode", "0");
						AKSLogs(5501, "" + iSN + "_" + iStation + "_" + iLayer);
					} catch (Exception e) {
						String str = errCodeManagement.getErrText(e.getMessage());
						eleR.addAttribute("errorCode", "1");
						eleR.addAttribute("errorText", str);
						eleR.addAttribute("actionCode", "0");
						AKSLogs(5500, "" + iSN + "_" + iStation + "_" + iLayer + "_" + str);
					}
				}
			} else {
				isUnknowCase = true;
				return null;
			}
			return MSG;
		} catch (Exception e) {
			if(iClient==null) {
				Element Mroot = MSG.getRootElement();
				Element eleR = Mroot.element("body").addElement("result");
				eleR.addAttribute("errorCode", "1");
				eleR.addAttribute("errorText", "工位信息获取失败");
				eleR.addAttribute("actionCode", "0");
				return MSG;
			}
			String str = errCodeManagement.getErrText(e.getMessage());
			System.out.println(str);
			return null;
		}

	}

	public void AKSLogs(int iType, String ilogClientNews) {
		SQLtool.AKSLogs(iType, ilogClientNews);
	}
	
	private m_panelSonResultState getErrCompsInfo(m_panelSonResultState iState, List<?> errComps) {
		if(errComps==null || errComps.size()<1) {
			return iState;
		}
		iState.errComps=new String[errComps.size()];
		iState.errCode=new String[errComps.size()];
		for (int n = 0; n < errComps.size(); n++) {
			String isnRpass = "0";
			try {
				isnRpass = ((Element) errComps.get(n)).attribute("bRpass").getValue();
			}catch(Exception e) {
				isnRpass = ((Element) errComps.get(n)).attribute("Rpass").getValue();
			}
			if (isnRpass.equals("0")) {// 240509 改为0的按照不良品获取 
				iState.errComps[n]=((Element) errComps.get(n)).attribute("comps").getValue();
				iState.errCode[n]=((Element) errComps.get(n)).attribute("errCode").getValue();
			}
			
		}
		return iState;
	}
	
	/**
	 * 	获取在加严清单中的位号
	 * @param iPos 
	 * @param t
	 * @return
	 * @throws Exception 
	 */
	private Vector<String> getSPIxRayListComps(String iPos) throws Exception {

		Vector<String> iXRComps = new Vector<String>();
		String iMasterNumber = null;
		iMasterNumber=sql.selectFirstValue(
				"select masterNumber from vOrderListPanel where sequence=" + iPos
						+ " and panelOrderNumber='" + iClient.activeOrderNumber + "'");
		if (iMasterNumber != null && iMasterNumber.length() > 0) {// 查询总成号
			JTable t = sql.select(
					"select partNumber,comps,materialNumber from SPIxRayList where partNumber='"
							+ iMasterNumber + "'");
			if (t != null && t.getRowCount() > 0) {// 下载加严清单中该总成的所有位号
				for (int m = 0; m < t.getRowCount(); m++) {
					String strXR = "" + t.getValueAt(m, 1);
					if (strXR != null && strXR.length() > 0
							&& (!strXR.equals("null"))) {
						iXRComps.addAll(Arrays.asList(strXR.split(",")));
					}
				}
				
			}

		}
		
		return iXRComps;
	}

	/**
	 * 	获取有复判的位号
	 * @param errComps
	 * @return
	 */
	private Vector<String> getRepairComps(List<?> errComps) {
		Vector<String> iRpComps = new Vector<String>();
		for (int n = 0; n < errComps.size(); n++) {
			String isnRpass = "0";
			try {
				isnRpass = ((Element) errComps.get(n)).attribute("bRpass").getValue();
			}catch(Exception e) {
				isnRpass = ((Element) errComps.get(n)).attribute("Rpass").getValue();
			}
			if (isnRpass.equals("1")) {//231201 从0改为1，SPI中，1代表RPASS
				String[] strComps = ((Element) errComps.get(n)).attribute("comps")
						.getValue().split(",");
				iRpComps.addAll(Arrays.asList(strComps));
			}
		}
		return iRpComps;
	}

}
